/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.service.evaluation;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.evaluation.prepare.PersonnelDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.PersonnelRepository;
import cn.ac.nercis.pes.repository.mapper.evaluation.PersonnelMapper;
import cn.ac.nercis.pes.repository.model.evaluation.PersonnelDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 人员（系统资产）信息服务类
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class PersonnelService {

    private final PersonnelRepository personnelRepository;

    @Autowired
    public PersonnelService(PersonnelRepository personnelRepository) {
        this.personnelRepository = personnelRepository;
    }

    public List<PersonnelDTO> findPersonnel(String systemId){
        return this.personnelRepository.findAllBySystemId(systemId)
                .stream()
                .map(PersonnelMapper.INSTANCE::toDTO)
                .collect(Collectors.toList());
    }

    public Result<PersonnelDTO> savePersonnel(PersonnelDTO personnel){
        if(StringUtils.isEmpty(personnel.getName())){
            personnel.setName("");
        }
        if(StringUtils.isEmpty(personnel.getRole())){
            personnel.setRole("");
        }
        try{
            if(StringUtils.isEmpty(personnel.getId())){
                return create(personnel);
            }else{
                return modify(personnel);
            }
        }catch (Exception e){
            log.error("保存人员信息出错：",e);
            return Result.failed();
        }
    }

    public Result<String> batchSavePersonnel(List<PersonnelDTO> data){
        Result<String> result = Result.success();
        for(PersonnelDTO item : data){
            Result<PersonnelDTO> itemResult = savePersonnel(item);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    public Result<String> deletePersonnel(String id){
        try{
            return this.personnelRepository.findById(id)
                    .map(personnelDO -> {
                        personnelRepository.delete(personnelDO);
                        return personnelDO;
                    })
                    .map(PersonnelDO::getId)
                    .map(Result::success)
                    .orElse(Result.failed());
        }catch (Exception ex){
            log.error("删除人员信息出错：",ex);
            return Result.failed();
        }
    }

    public Result<String> batchDeletePersonnel(Set<String> ids){
        Result<String> result = Result.success();
        for(String id : ids){
            Result<String> itemResult = deletePersonnel(id);
            if(!itemResult.isSuccess()){
                result = itemResult;
                break;
            }
        }
        return result;
    }

    private Result<PersonnelDTO> create(PersonnelDTO personnel){
        return Optional.of(PersonnelMapper.INSTANCE.toDO(personnel))
                .map(e->{
                    e.setCreateTime(LocalDateTime.now());
                    return e;
                })
                .map(personnelRepository::save)
                .map(PersonnelMapper.INSTANCE::toDTO)
                .map(Result::success)
                .orElse(Result.failed());
    }

    private Result<PersonnelDTO> modify(PersonnelDTO personnel){
        PersonnelDO source = this.personnelRepository.findById(personnel.getId()).orElse(null);
        if(Objects.isNull(source)){
            return Result.failed(ResultCode.NOT_FOUND);
        }
        return Optional.of(source)
                .map(s->{
                    s.setName(personnel.getName());
                    s.setRole(personnel.getRole());
                    s.setDesc(personnel.getDesc());
                    s.setTel(personnel.getTel());
                    s.setModifyTime(LocalDateTime.now());
                    return s;
                })
                .map(personnelRepository::save)
                .map(PersonnelMapper.INSTANCE::toDTO)
                .map(Result::success)
                .orElse(Result.failed(ResultCode.FAIL));
    }
}